//--------------NAME OF APPLICATION-------------------
var path = window.location.pathname.substr(1).split('/');
var disableSafetyLeaveForPages = [ '/tote/edit/' ];

var applicationName = '';
if (path.length > 0 && path[0] != '')
	applicationName = '/' + path[0];

// MISC
var smthChanged = false;

function safetyLeave() {
	$(window).ready(function() {
		var isSafetyLeave = true;
		for (i in disableSafetyLeaveForPages) {
			if (document.URL.indexOf(disableSafetyLeaveForPages[i]) != -1) {
				isSafetyLeave = false;
			}
		}
		if (isSafetyLeave) {
			$(':input').not('[name="query"]').change(function() {
				smthChanged = true;
			});

			window.onbeforeunload = function() {
				if (smthChanged) {
					/*
					 * Doesn't show this message in FF. See
					 * https://bugzilla.mozilla.org/show_bug.cgi?id=588292
					 */
					return "Attention!!! You haven't saved your changes.";
				}
			};
		}

	});
}

function sendFeedback() {

	$.post(applicationName + '/feedback', {
		feedBackText : $('#fbtext').val(),
		page : window.location.pathname
	});

	$('#fbtext').val('');
	$('#FBModal').modal('hide');
}

function createErrorMesage() {
	$('#operation_result_msg').append(
			'<div id="failure_msg" class="alert alert-error">'
					+ '<button class="close" data-dismiss="alert">×</button>'
					+ '<strong>Error! </strong>'
					+ 'There were some error while validating fiels.'
					+ '</div>');
}

function doSubmit(formName, action) {
	for (instance in CKEDITOR.instances) {
		if (CKEDITOR.instances[instance]) {
			CKEDITOR.instances[instance].updateElement();
		}
	}

	if (action != null) {
		document.forms[formName].setAttribute('action', action);
	}
	smthChanged = false;
	if (document.forms[formName].onsubmit) {
		if (document.forms[formName].onsubmit()) {
			$('#success_msg').remove();
			document.forms[formName].submit();
		} else {
			$('#success_msg').remove();
			$('#failure_msg').remove();
			createErrorMesage();
		}
	} else {
		$('#success_msg').remove();
		document.forms[formName].submit();
	}
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// CKEDITOR

function showCKEditor(id, fullEditor) {
	var cke = document.getElementById(id);
	if (cke != null) {
		replaceTextarea(id, fullEditor);
		// !!
		/*
		 * ckeInstance = CKEDITOR.instances[id]; ckeInstance.on( 'change',
		 * function(e) {
		 * 
		 * selectedElems = $("textarea[id="+ id +"]");
		 * 
		 * if(selectedElems.length<=0) { return; }
		 * 
		 * textArea = selectedElems[0];
		 * 
		 * if(textArea == undefined || textArea == null){ alert("Failed during
		 * detecting text area"); return; }
		 * if(ckeInstance.document.getBody().getChildCount() > 0){
		 * if(ckeInstance.document.getBody().getChildCount() > 0){
		 * //textArea.value =
		 * ckeInstance.document.getBody().getChild(0).getHtml(); textArea.value =
		 * ckeInstance.document.getBody().getHtml(); textArea.blur(); } }
		 * smthChanged = true; // For safety leaving });
		 */
		// !!
		// setTimeout(function a(){
		// CKEDITOR.instances[id].focus();
		//			
		// },500);
	}
}

function hideCKEditor(id) {
	var cke = document.getElementById(id);
	if (cke != null) {
		var ckeInstance = CKEDITOR.instances[id];
		if (ckeInstance != null) {
			if (ckeInstance.document.getBody().getChildCount() > 0) {
				// cke.innerHTML =
				// ckeInstance.document.getBody().getChild(0).getHtml();
				cke.innerHTML = ckeInstance.document.getBody().getHtml();
			} else {
				cke.innerHTML = "";
			}
			// unregister CKEditor instance
			CKEDITOR.remove(ckeInstance);
			// remove span element from DOM tree
			var ckeSpan = document.getElementById('cke_' + id);
			ckeSpan.parentNode.removeChild(ckeSpan);

			ckeInstance.destroy(true);

		}
	}
}

function replaceTextarea(ckeId, fullEditor) {
	// if(CKEDITOR.instances[ckeId]) {
	// CKEDITOR.instances[ckeId].destroy();
	// }
	if (fullEditor) {
		CKEDITOR.replace(ckeId, {
			width : '99%',
			height : '600px'
		});
	} else {
		CKEDITOR.replace(ckeId, {
			width : '98%',
			height : '100px',
			customConfig : 'ck_answer_config.js'
		});
	}

}

// VALIDATION

function createValidator(elemId, text, focusElem) {
	eval("valid_"
			+ elemId
			+ "_content = ( typeof valid_"
			+ elemId
			+ "_content === \"undefined\" ? new LiveValidation(document.getElementById(\""
			+ elemId + "_content\")) : valid_" + elemId + "_content);");
	eval("valid_"
			+ elemId
			+ "_content.onValid = function(){this.insertMessage(document.createElement(\"span\")); this.addFieldClass();};");
	eval("valid_"
			+ elemId
			+ "_content.add(Validate.Custom, {failureMessage: \""
			+ text
			+ "\", against: function validateCKEWrapper(value, paramsObj){return validateCKE(value, paramsObj)}})");
	eval("valid_" + elemId
			+ "_content.add(Validate.Presence, {failureMessage: \"" + text
			+ "\"});");
	eval("valid_"
			+ elemId
			+ "_content.onInvalid = function(){ this.insertMessage( this.createMessageSpan() ); this.addFieldClass(); focusInvalidField("
			+ focusElem + ");};");

}

function removeValidator(elemId) {
	eval("valid_" + elemId + "_content.destroy(true);");
	eval("delete valid_" + elemId + "_content;");
}

function focusInvalidField(elem) {
	$('a[href="#tabQuestions"]').tab('show');
	jQuery.fn.exists = function() {
		return this.length > 0;
	};
	if ($('#' + elem.id).exists()) {
		$('#' + elem.id).focus();
	} else {
		$('#' + elem).focus();
	}

}


function showModal(modalElem) {
	modalElem.modal({
		backdrop : true,
		keyboard : true,
		show : true
	});
}

// MAIN MENU
function setActiveMainMenuElem(menuId) {
	$('div.container-fluid>ul>li#homeMenu').removeClass('active');
	$('#headerMenu>li').removeClass('active');
	$('#headerMenu>#' + menuId).addClass('active');
}

function changeCheckedState(select, elem) {
	$("input[id*=" + select + "][type='checkbox']").attr("checked",
			elem.checked);
}

function convertIdForJQuery(id) {
	return id.replace(/\./g, '\\.');
}

function scrollUp() {
	/* set variables locally for increased performance */
	var scroll_timer;
	var displayed = false;
	var $message = $('#message a');
	var $window = $(window);
	var top = $(document.body).children(0).position().top;

	/* react to scroll event on window */
	$window.scroll(function() {
		window.clearTimeout(scroll_timer);
		scroll_timer = window.setTimeout(function() {
			if ($window.scrollTop() <= top) {
				displayed = false;
				$message.fadeOut(500);
			} else if (displayed == false) {
				displayed = true;
				$message.stop(true, true).show().click(function() {
					$message.fadeOut(500);
				});
			}
		}, 100);
	});
}

function changePassword() {
	$('#changePassForm').attr('action', applicationName + '/profile/password');

	$('#changePassForm').submit();

	$('#oldP').val('');
	$('#newP').val('');
	$('#newPR').val('');

	$('#ChPassModal').modal('hide');
}

function changeName() {
	$('#changeNameForm').attr('action', applicationName + '/profile/name');

	$('#changeNameForm').submit();

	$('#pass').val('');
	$('#newName').val('');

	$('#ChNameModal').modal('hide');
}

function showSimpleEditor(id, fixValidation) {
	var editor = CKEDITOR.replace(id, {
		toolbar : 'Basic'
	});
	if (fixValidation) {
		editor.on('change', function() {
			editor.updateElement();
		});
	}
	return editor;
}

function showCommentEditor(id) {
	var editor = CKEDITOR.replace(id, {
		toolbar : 'Basic',
		removePlugins : 'elementspath',
		resize_enabled : false,
	});
	editor.on('change', function() {
		editor.updateElement();
	});

	return editor;
}

function blockUI() {
	$.blockUI({
		css : {
			border : 'none',
			padding : '15px',
			backgroundColor : '#000',
			'-webkit-border-radius' : '10px',
			'-moz-border-radius' : '10px',
			opacity : .5,
			color : '#fff'
		}
	});
}

function unblockUI() {
	$.unblockUI();
}

function restrictDateRange(input) {
	if (input.id == 'endDate') {
		return {
			minDate : $('#beginDate').datepicker("getDate")
		};
	} else if (input.id == 'beginDate') {
		return {
			maxDate : $('#endDate').datepicker("getDate")
		};
	}
}